import axios, { type AxiosInstance } from 'axios';
import router from '../router';
import { clearAuth } from './auth';

const request: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器：自动添加token
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  response => response.data,
  error => {
    const status = error.response?.status || error.response?.statusCode;
    const currentPath = router.currentRoute.value?.path || window.location.pathname;
    
    // 处理401未授权错误（token过期或无效）
    if (status === 401) {
      console.warn('Token已过期或无效，正在跳转到登录页...');
      
      // 清除本地存储的认证信息
      clearAuth();
      
      // 确保跳转到登录页（避免重复跳转）
      if (currentPath !== '/login' && currentPath !== '/register') {
        // 使用setTimeout确保清除操作完成后再跳转
        setTimeout(() => {
          router.push('/login').then(() => {
            console.log('已跳转到登录页面');
          }).catch((err) => {
            console.error('路由跳转失败，使用强制跳转:', err);
            // 如果路由跳转失败，使用window.location强制跳转
            window.location.href = '/login';
          });
        }, 100);
      }
      
      // 返回错误信息
      const errorResponse = {
        success: false,
        message: error.response?.data?.message || '登录已过期，请重新登录',
        code: 401
      };
      return Promise.reject(errorResponse);
    }
    
    // 处理其他错误
    console.error('请求失败:', error);
    const errorResponse = {
      success: false,
      message: error.response?.data?.message || error.message || '网络错误',
      data: error.response?.data
    };
    return Promise.reject(errorResponse);
  }
);

export default request;